﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WebApplication1.MyFilters
{
    /// <summary>
    /// 自定义异常过滤器 只有未被处理的异常才会在这里处理
    /// </summary>
    public class MyExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<MyExceptionFilter> _logger;
        private readonly IHostEnvironment _env;

        public MyExceptionFilter(ILogger<MyExceptionFilter> logger, IHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            Exception exception = context.Exception;
            _logger.LogError(exception, "发生异常");
            string message;
            if (_env.IsDevelopment())
            {
                message = exception.Message;
            }
            else
            {
                message = "发生了一个错误";
            }
            ObjectResult result = new ObjectResult(new
            {
                StatusCode = 500,
                Message = message
            })
            {
                StatusCode = 500
            };
            context.Result = result;
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
